<script>
import * as Elements from '@/store/elements'
import * as Ui from '@/store/elementui'

/**
 * 包装了所有的form-filed
 * 拦截所有的input事件，只返回change事件
 *
 *   props: {
 *      widget: string 组件
 *      translate: 数值转换函数
 *
 *      ?rules: array<rule> 验证
 *      ?required: bool
 *      ?options: array<option>
 *      ?border: el-form-item
 *
 *      label-width: string
 *      ...field
 *   }
 */
export default {
  functional: true,
  render (h, context) {

    const { props } = context

    let element = Ui.WIDGETS.pick(props[Elements.WIDGET])

    if (!element) {
      console.log('render field error:', props)
      return undefined
    }

    let children

    if (Array.isArray(props[Ui.OPTIONS]) && element[Ui.OPTION]) {
      let fn = element[Ui.OPTION]
      children = props[Ui.OPTIONS].map((op) => {
        let ele = fn(op)
        return h(ele.tag, {
          props: {
            ...ele
          }
        }, ele.text)
      })
    }

    const form = {
      ...props.border,
      prop: props.name,
      rules: props.rules,
      required: props.required
    }

    if (props[Ui.LABEL_WIDTH] !== 'none') form.label = props.label

    let tag = element[Elements.TAG]

    if (!tag) {
      console.log('render tag error', props)
      return undefined
    }

    let item = {
      ...(element[Elements.DEFINITION] || {}),
      ...props
    }

    let on = {
      ...context.listeners
    }

    //
    if (typeof item.translate === 'function') {
      let input = context.listeners.input
      let change = context.listeners.change
      if (input) on.input = v => input(item.translate(v))
      if (change) on.change = v => change(item.translate(v))
    }

    // 在functional中最后绘制XHTML实体标签时，需要传入attrs
    return h('el-form-item', {
      props: {
        ...form
      }
    }, [h(tag, {
      props: item,
      attrs: item,
      on
      }, children)]
    )
  }
}

</script>
